#!/usr/bin/env bash

include "libs/changelog.sh"
include "libs/database.sh"

function auto_update:is_git_repo()
{
    pushd $(dirname $0) 1>/dev/null
    git branch 1>/dev/null 2>&1
    ret=$?
    popd 1>/dev/null
    return $?
}

function auto_update:fetch_new()
{
    pushd $(dirname $0) 1>/dev/null
    old_version=$(database:global_get git_repo_version)
    if [ "$old_version" == "" ]; then
        old_version=$(git rev-parse HEAD)
    fi

    if git fetch origin > /dev/null 2>&1; then
        database:global_load
        current_version=$(git rev-parse origin/master)
        if [ "$current_version" != "$old_version" ]; then
            database:global_set git_repo_new true
        fi
        database:global_save
    fi
    popd 1>/dev/null
}

function auto_update:check_new()
{
    database:global_load
    if [ "true" == "$(database:global_get git_repo_new)" ]; then
        read -r -p "[ohos-tool] 有新的版本，你想更新么？ (y/n) " option
        if [ "$option" = "y" ]; then
            auto_update:update
            return
        fi
    fi
    return 1
}

function auto_update:update()
{
    pushd $(dirname 0) 1>/dev/null
    if [ "$(git name-rev --no-undefined --name-only --exclude="remotes/*" HEAD)" != "master" ]; then
        false || report "ohos-tool仓库分支名不是master"
        popd 1>/dev/null
        return 1
    fi

    if [ "$(git status -s | wc -l)" != "0" ]; then
        false || report "ohos-tool仓库有修改"
        popd 1>/dev/null
        return 1
    fi

    database:global_load
    old_version=$(database:global_get git_repo_version)
    if [ "$old_version" == "" ]; then
        old_version=$(git rev-parse HEAD)
    fi
    git reset --hard origin/master
    git submodule init
    git submodule update
    current_version=$(git rev-parse HEAD)
    changelog:display $old_version $current_version
    database:global_set git_repo_version $current_version
    database:global_set git_repo_new false
    database:global_save
    popd 1>/dev/null
}
